import common.djangoversion
import os, logging as log
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from common.entities import Attachment, AttachmentData, AttachmentTag
from base64 import b64encode
from datetime import datetime
from google.appengine.ext.webapp import template
from urllib import unquote
from common.paging import PagedQuery

def get_tags():
    tags = AttachmentTag.all().order('tag_name').fetch(30)
    for x in tags: x.count = len(x.file_list) % 3
    return tags

class MainPage(webapp.RequestHandler):
    def get(self):
        path = os.path.join(os.path.dirname(__file__), 'templates/springfield.html')
        self.response.out.write(template.render(path, {'showlist':False, 'tags':get_tags()}))

class ShowTaggedPage(webapp.RequestHandler):
    def get(self, tag_name):
        tag_name = unquote(tag_name)
        page_no = self.request.get('page_no')
        if not page_no: page_no = 1

        tag = AttachmentTag.all().filter('tag_name =', tag_name).get()

        tag.file_list = sorted(tag.file_list)
        path = os.path.join(os.path.dirname(__file__), 'templates/springfield.html')
        self.response.out.write(template.render(path, {'showtag':True, 'tag':tag, 'tags':get_tags()}))

        
class SearchPage(webapp.RequestHandler):
    def get(self, term=None):
        if not term: term= self.request.get('term')
        term = unquote(term)

        page_no = self.request.get('page_no')
        if not page_no: page_no = 1

        if '@' in term:
            q = Attachment.all().filter('to =', term)
        else:
            q = Attachment.all().filter('domain =', term)

        pagedQuery = PagedQuery(q, 10)
        pagedQuery.order('file_name')

        attachments = pagedQuery.fetch_page(page_no)

        path = os.path.join(os.path.dirname(__file__), 'templates/springfield.html')
        self.response.out.write(template.render(path, {'tags': get_tags(),
                                                       'attachments':attachments, 
                                                       'showlist':True, 
                                                       'search_term':term, 
                                                       'page_count':pagedQuery.page_count(),
                                                       'search_count': pagedQuery.count(),
                                                       'first_displayed' : (page_no-1) * 10 + 1,
                                                       'last_displayed' :  (page_no-1) * 10 + len(attachments),
                                                       'prev_no' : page_no - 1,
                                                       'next_no' : page_no + 1,
                                                       'prev_class': '' if pagedQuery.has_page(page_no-1) else 'inactive',
                                                       'next_class': '' if pagedQuery.has_page(page_no+1) else 'inactive',
                                                       'page_no': page_no }))


class ServePage(webapp.RequestHandler):

    def get(self, name):
        name = unquote(name)
        log.info('Getting attachment %s' % name)

        data = AttachmentData.all().filter('file_name =', name).order('order').fetch(limit=10)

        self.response.headers['Content-Type'] = 'application/pdf'
        self.response.headers['Content-Transfer-Encoding'] = 'Binary'
        self.response.headers['Content-disposition'] = 'attachment; filename="%s.pdf"' % name

        for ad in data:
            self.response.out.write(ad.data)

application = webapp.WSGIApplication(
                                     [('/', MainPage),
                                      (r'/showtagged/([^/]+)?', ShowTaggedPage),
                                      (r'/search/([^/]+)?', SearchPage),
                                      (r'/serve/([^/]+)?', ServePage),
                                      (r'/search?', SearchPage)],
                                     debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
